<?php

use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\LexerConfig;

class DataController extends \Phalcon\Mvc\Controller
{

    const LOOP_CNT = 1;

    public function indexAction() {
        echo 'this is index.<br>';
        echo '<pre>';
        print_r($this->request->get());
        echo '</pre>';
 
    }
    
    public function queryAction() {
        $res = Label::find(array(
            "sort" => array("cno" => 1),
         ));

        echo 'label：'. count($res) . '件<br>';
        foreach($res as $doc) {
            echo '<pre>';
            //print_r($doc);
	     print_r(get_object_vars($doc));
            echo '</pre>';
        }

        $conds = array();
         
        $params = $this->request->get();
        foreach($params as $key=>$value) {
            if ($key != '_url') {
                $conds[$key] = $value;
             }
        }
       
        $conditions = implode(' and ', $conds);
         // multi conditions is AND
        $res = Raw::find(array(
            'conditions' => $conds,
            "bind" => $params,
            "sort" => array("no" => 1),
            "limit" => 10,
        ));

//        $res = Raw::query()
//               ->where($conditions)
//               ->bind($params)
//               ->order('no')
//               ->execute();

        echo 'rawdata：'. count($res) . '/' . Raw::count() . '件<br>';

        foreach($res as $doc) {
            echo '<pre>';
            //print_r($doc);
	     print_r(get_object_vars($doc));
            echo '</pre>';
        }

    }

    public function clearAction() {

        $link = new MongoClient();
        //DB
        $db = $link->total;
        //削除
        $db->label->remove();

        echo "Great, label was cleared successfully!<br>";

        $db->raw->remove();
        echo "Great, rawdata was cleared successfully!<br>";


    }


    public function importlAction() {
 
set_time_limit(60);

         // todo
        $filel = __DIR__ . '/label_l.csv';
        $filer = __DIR__ . '/rawdata_l.csv';

        $this->importLabel($filel);
        $this->importRawdata($filer);

   }

    public function importAction() {
 
         // todo
        $filel = __DIR__ . '/label.csv';
        $filer = __DIR__ . '/rawdata.csv';

        $this->importLabel($filel);
        $this->importRawdata($filer);

   }

    public function import2Action() {
 
        $lexer = new Lexer(new LexerConfig());
        $interpreter = new Interpreter();

        
        $interpreter->addObserver(function(array $row) use ($label) {
            if (!is_numeric($row[0]))
                return;

            $label = new Label();
            $label->cno = (int)$row[0];
            $label->cno2 = empty($row[1]) ? null : $row[1];
            $label->la = $row[2];
            $label->cd = empty($row[3]) ? null : $row[3];
            $label->nm = empty($row[4]) ? null : $row[4];
            $label->nm2 = empty($row[5]) ? null : $row[5];
            $label->t = empty($row[6]) ? null : $row[6];
              
            $cat = array();
            $i = 8;
            while(($row[$i]) != '') {
                $cat[] = array('no'=>$i-7, 'nm'=>$row[$i]);
                $i++;
              }
            $label->cat = $cat;

            if ($label->save()) {
                echo "Great, label " . $label->cno ."was saved successfully!\n";
            } else {
                echo "Umh, We can't store label right now: \n";
	         foreach ($user->getMessages() as $message) {
		     echo $message, "\n";
	          }

              }
         });
    
        $lexer->parse(__DIR__ . '/label.csv', $interpreter);

        echo 'import is completed.';

    }

    private function importLabel($file) {

        $data = file_get_contents($file);
        $data = mb_convert_encoding($data, 'UTF-8', 'sjis');
        $temp = tmpfile();
        fwrite($temp, $data);

    for ($n=1;$n<=self::LOOP_CNT;$n++) {

        rewind($temp);
 
        while (($row = fgetcsv($temp, 0, ",")) !== FALSE) {

            if (!is_numeric($row[0]))
                continue;

            $label = new Label();

            $label->cno = (int)$row[0];
            $label->cno2 = empty($row[1]) ? null : $row[1];
            $label->la = $row[2];
            $label->cd = empty($row[3]) ? null : $row[3];
            $label->nm = empty($row[4]) ? null : $row[4];
            $label->nm2 = empty($row[5]) ? null : $row[5];
            $label->t = empty($row[6]) ? null : $row[6];
              
            $cat = array();
            $i = 8;
            while(!empty($row[$i])) {
                $cat[] = array('no'=>$i-7, 'nm'=>$row[$i]);
                $i++;
              }
            $label->cat = $cat;

            if ($label->save()) {
//                echo "Great, label " . $label->cno ."was saved successfully!\n";
            } else {
                echo "Umh, We can't store label right now: \n";
	         foreach ($user->getMessages() as $message) {
		     echo $message, "\n";
	          }

              }
         }
    }
        fclose($temp);

        echo 'label is imported.<br>';


    }


    private function importRawdata($file) {

        $data = file_get_contents($file);
        $data = mb_convert_encoding($data, 'UTF-8', 'sjis');
        $temp = tmpfile();
        fwrite($temp, $data);


    for ($n=1;$n<=self::LOOP_CNT;$n++) {
        rewind($temp);
 
        $rowno = 1;
        $labels = fgetcsv($temp, 0, ",");
        $colsize = count($labels);

        while (($row = fgetcsv($temp, 0, ",")) !== FALSE) {

            $raw = new Raw();

            for($i=0; $i<$colsize; $i++) {
                $raw->$labels[$i] = $row[$i];
             }

            if ($raw->save()) {
//                echo "Great, raw " . $rowno ."was saved successfully!\n";
            } else {
                echo "Umh, We can't store rawdata right now: \n";
	         foreach ($user->getMessages() as $message) {
		     echo $message, "\n";
	          }

              }

            $rowno++;
         }
    }

        fclose($temp);

        echo 'rawdata is imported.<br>';
    }


}         


